package com.gm.wholesale.module.aftersale.ui;

import android.text.Editable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.gm.commonlib.base.baseBean.BaseResp;
import com.gm.commonlib.base.baseView.IBaseView;
import com.gm.commonlib.base.baseui.baseFragment.BaseFragment;
import com.gm.commonlib.network.BaseHttpObserver;
import com.gm.commonlib.util.numberUtils.NumberUtils;
import com.gm.commonlib.views.superview.SuperTextView;
import com.gm.commonlib.views.toast.ToastUtil;
import com.gm.wholesale.R;
import com.gm.wholesale.module.aftersale.view.AftersaleListItem;
import com.gm.wholesale.module.evenbus.EvenBusUtil;
import com.gm.wholesale.module.main.ui.MainActivity;
import com.gm.wholesale.module.order.bean.CreateAftersaleReq;
import com.gm.wholesale.module.order.bean.OrderBean;
import com.gm.wholesale.module.order.bean.OrderDetailBean;
import com.gm.wholesale.module.order.model.OrderModel;
import com.gm.wholesale.util.ViewUtil;
import com.gm.wholesale.view.MyTextWatcher;
import com.gm.wholesale.view.NumberInputView;
import com.youth.banner.util.LogUtils;

import java.util.ArrayList;
import java.util.List;

public class AftersaleFragment extends BaseFragment {
    private LinearLayout mainView;
    private TextView totalPriceTv;
    private SuperTextView payMoneyTv;
    private NumberInputView numberInputView;
    OrderDetailBean mOrderDetailsDTOS;
    private int mCurrentPos;

    private List<AftersaleListItem> items = new ArrayList<>();

    @Override
    protected void onCreateContentBody(ViewGroup parent) {
        View view = LayoutInflater.from(context).inflate(R.layout.fragment_aftersale, parent);
        initView(view);
        mOrderDetailsDTOS = (OrderDetailBean) getArguments().getSerializable("data");
        if (mOrderDetailsDTOS!=null){
            showView(mOrderDetailsDTOS.getHandelOrderDetailsDTO());
        }

        showView(mOrderDetailsDTOS.getHandelOrderDetailsDTO());
       view.findViewById(R.id.backImage).setOnClickListener(v -> ViewUtil.finishFragment(getActivity(),AftersaleFragment.this));
    }



    private void initView(View view) {
        mainView = view.findViewById(R.id.mainView);
        totalPriceTv = view.findViewById(R.id.totalPriceTv);
        payMoneyTv = view.findViewById(R.id.payMoneyTv);
        numberInputView = view.findViewById(R.id.numberInputView);
        numberInputView.setINumberView(() -> {
            if (mCurrentPos == items.size() - 1) {
                return;
            }
            EditText nextEditText = items.get(mCurrentPos + 1).afterSaleNumEd;
            String nextInputs = nextEditText.getText().toString();
            nextEditText.requestFocus();
            numberInputView.bindEdiText(nextEditText, nextInputs);
        });
        payMoneyTv.setOnClickListener(view1 -> toCreateAfterOrder());
    }

    private void toCreateAfterOrder() {
        try {
            List<CreateAftersaleReq.ItemsDTO> itemsDTOS = new ArrayList<>();
            for (AftersaleListItem item : aftersaleListItems) {
                OrderDetailBean.OrderDetailsDTO orderDetailsDTO = item.getInputData();
                if (orderDetailsDTO == null) {
                    return;
                }
                if (orderDetailsDTO.getAfterNum() <= 0) {
                    continue;
                }
                CreateAftersaleReq.ItemsDTO itemsDTO = new CreateAftersaleReq.ItemsDTO();
                itemsDTO.setOrderLineId(orderDetailsDTO.getOrderLineId());
                itemsDTO.setQuantity(orderDetailsDTO.getAfterNum() + "");
                itemsDTOS.add(itemsDTO);
            }
            if (itemsDTOS.isEmpty()) {
                ToastUtil.showToast("请输入退货数量");
                return;
            }

            CreateAftersaleReq createAftersaleReq = new CreateAftersaleReq();
            createAftersaleReq.setItems(itemsDTOS);

            OrderModel.createAftersale((IBaseView) getActivity(), mOrderDetailsDTOS.getOrderInfo().getOrderId(),
                    createAftersaleReq, new BaseHttpObserver<BaseResp>() {
                        @Override
                        protected void handleResultOkResp(BaseResp resp) {
                            ToastUtil.showToast("操作成功");

                            MainActivity activity = (MainActivity) getActivity();
                            ViewUtil.finishFragment(activity,AftersaleFragment.this);
                            if (mOrderDetailsDTOS == null
                                    || mOrderDetailsDTOS.getOrderInfo() == null) {
                                return;
                            }
                           OrderBean orderBean=new OrderBean();
                            orderBean.setOrderId(mOrderDetailsDTOS.getOrderInfo().getOrderId());
                            EvenBusUtil.updateOrderDetail(orderBean);

                        }
                    });
        } catch (Exception e) {
            LogUtils.d("eeeeeee: " + e.toString());
            ToastUtil.showToast("数据异常");
        }

    }

    private List<AftersaleListItem> aftersaleListItems = new ArrayList<>();

    public void showView(List<OrderDetailBean.OrderDetailsDTO> datas) {
        if (datas==null) return;
        aftersaleListItems.clear();
        mainView.removeAllViews();
        int i = 0;
        for (OrderDetailBean.OrderDetailsDTO detailsDTO : datas) {
            String nums=detailsDTO.getQuantity();
            if (TextUtils.isEmpty(nums) || Double.parseDouble(nums)<=0
            || detailsDTO.isAfterSaleData()){
                continue;
            }
            AftersaleListItem item = new AftersaleListItem(getActivity());
            items.add(item);
            item.setTag(i);
            aftersaleListItems.add(item);
            if (i == 0) {
                numberInputView.bindEdiText(item.afterSaleNumEd, "");
                item.afterSaleNumEd.requestFocus();
            }
            i++;
            item.afterSaleNumEd.setOnFocusChangeListener((view, b) -> {
                if (b) {
                    numberInputView.bindEdiText(item.afterSaleNumEd, "");
                    if (item.getTag() != null) {
                        mCurrentPos = (int) item.getTag();
                    }

                }
            });
            item.afterSaleNumEd.addTextChangedListener(
                    new MyTextWatcher() {
                        @Override
                        public void afterTextChanged(Editable editable) {
                            showTotalMoney();
                        }
                    }
            );
            item.showView(detailsDTO);
            mainView.addView(item);
        }
    }

    private void showTotalMoney() {
        double totalMoney = 0.0;
        if (aftersaleListItems == null) {
            return;
        }
        for (AftersaleListItem aftersaleListItem : aftersaleListItems) {
            double inputNum = aftersaleListItem.getInputNumberData();
            OrderDetailBean.OrderDetailsDTO orderDetailsDTO = aftersaleListItem.mData;
            if (orderDetailsDTO == null || orderDetailsDTO.getUnitPrice() == null) {
                return;
            }
            double price = Double.parseDouble(orderDetailsDTO.getUnitPrice());
            double oneGoodPrice = NumberUtils.mul(inputNum, price);
            totalMoney = NumberUtils.addDouble(totalMoney, oneGoodPrice);

        }
        totalPriceTv.setText(NumberUtils.getMoneyString(totalMoney));

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mainView!=null){
            mainView.removeAllViews();
        }
        aftersaleListItems.clear();

    }
}
